#coding=utf-8
#encoding=utf-8

from matplotlib import pyplot as plt
import numpy as np
#import argparse
import cv2
import os

#ap = argparse.ArgumentParser()
#ap.add_argument("-i","--image",required = True, help = "Path to the image")
#args = vars(ap.parse_args())

def count_histogram(img):
    image = cv2.imread(img)
    print "width: %d pixels" % (image.shape[1])
    print "height: %d pixels" % (image.shape[0])
    print "channels: %d pixels" % (image.shape[2])

    chans=cv2.split(image)
    colors=("b","g","r")

    plt.figure()
    plt.title("Flattened Color Histogram")
    plt.xlabel("Bins")
    plt.ylabel("# of Pixels")

    for (chan,color) in zip(chans,colors):
        hist=cv2.calcHist([chan],[0],None,[256],[0,256])
        plt.plot(hist,color=color)
        plt.xlim([0,256])
    if os.path.isfile('./screen_histogram.png'):
        os.remove('./screen_histogram.png')
    plt.savefig('screen_histogram.png')

def BGR_feature(img):
    #image = cv2.imread(img)
    #BGR_f = {'Bmax':[],'Gmax':[],'Rmax':[]}
    BGR_f = {}
    image = img
    hist = cv2.calcHist([image],[0],None,[256],[0.0,255.0])
    BGR_f['Bmax'] = np.where(hist==hist.max(0))[0][0]
    hist = cv2.calcHist([image],[1],None,[256],[0.0,255.0])
    BGR_f['Gmax'] = np.where(hist==hist.max(0))[0][0]
    hist = cv2.calcHist([image],[2],None,[256],[0.0,255.0])
    BGR_f['Rmax'] = np.where(hist==hist.max(0))[0][0]
    return BGR_f

def tv_contours(img):
    image=cv2.imread(img)
    screen = {}
    adjust = {}
    screen_no = 0
    #缩小原图尺寸，加速运算
    #ratio = image.shape[0] / 300
    #orig = image.copy()
    #image = img_resize(image, height = 300)
    #二值化图片
    gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    #计算出边框
    #gray = cv2.bilateralFilter(gray, 10, 20 ,20)
    ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY) 
    
    edged = cv2.Canny(gray, 30, 50)
    if os.path.isfile('./screen_edged.jpg'):
        os.remove('./screen_edged.jpg')
    cv2.imwrite('screen_edged.jpg',edged)
    contours, hierarchy = cv2.findContours(binary.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    #找到最大的几个框
    contours = sorted(contours, key = cv2.contourArea, reverse = True)[:10]
    screenCnt = None
    #用于计算方框面积
    cArea = 0
    #用于计算几个屏幕的红、绿、蓝最小值
    RR=255.00
    GG=255.00
    BB=255.00
   #找到4个角点的框
    for c in contours:
       peri = cv2.arcLength(c, True)
       approx = cv2.approxPolyDP(c, 0.02 * peri, True)
       if len(approx)==4:
           #屏幕编号不是第一个，且面积小于前一个的80%即停止搜索
           if screen_no > 1 and cv2.contourArea(c)/cArea < 0.7:
               break
           else:
               #记录搜索到的屏幕外框数组和面积
               screenCnt = approx
               screen_no = screen_no +1 
               print ('********',approx)
               print cv2.contourArea(c)
               cutimg = image.copy()[approx.min(0)[0][1]:approx.max(0)[0][1],approx.min(0)[0][0]:approx.max(0)[0][0]]
               cv2.drawContours(image, [screenCnt], -1, (0,0,255),3)
               #cv2.imshow('cut',cutimg)
               #cv2.waitKey(0)
               #计算单屏rgb特征值
               BGR = BGR_feature(cutimg)
               screen[screen_no] = BGR
               font=cv2.FONT_HERSHEY_SIMPLEX
               cv2.putText(image,
                       str(screen_no),(approx.min(0)[0][0]+100,approx.min(0)[0][1]+100),font,2,(0,0,255),2)
               if BGR['Rmax'] < RR:
                   RR = BGR['Rmax']
               if BGR['Gmax'] < GG:
                  GG = BGR['Gmax']
               if BGR['Bmax'] < BB:
                  BB = BGR['Bmax']
               print (RR,GG,BB)
               for scrn in screen:
                   #print screen[scrn]['Rmax']
                   R = (RR-float(screen[scrn]['Rmax'])) / float(screen[scrn]['Rmax'])
                   G = (GG-float(screen[scrn]['Gmax'])) / float(screen[scrn]['Gmax'])
                   B = (BB-float(screen[scrn]['Bmax'])) / float(screen[scrn]['Bmax'])
                   print (screen[scrn]['Rmax'],RR)
                   adjust[scrn] =  {'R':round(R,2),'G':round(G,2),'B':round(B,2)}
               cArea = cv2.contourArea(c)
    #adjust is a json contains param to adjust for each screen
    print adjust
   # for cont in contours:
   #     print (cont)
   # print (contours[7])
   # print (contours[8])
    if os.path.isfile('./screen_contours.jpg'):
        os.remove('./screen_contours.jpg')
    #图片如果太大无法通过微信发送，缩小原图。
    imgR=1200.0/image.shape[1]
    img_dim = (1200,int(image.shape[0]*imgR))
    print ('img dim:',img_dim)
    img_resized=cv2.resize(image, img_dim, interpolation=cv2.INTER_AREA)
    cv2.imwrite('screen_contours.jpg',img_resized)
    #cv2.imshow("image contour", image)
    #cv2.waitKey(0)
    return screen,adjust

def img_resize(img, height):
    pass

#cv2.waitKey(0)
#cv2.destroyAllWindows()


